﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using com.lover.astd.common.config;
using com.lover.astd.common.manager;
using com.lover.astd.common.model;
using com.lover.astd.common.model.enumer;
using com.lover.astd.game.ui.server;
using com.lover.common;
using com.lover.astd.common.partner;
using System.Net;
using AxSHDocVw;
using mshtml;

namespace com.lover.astd.game.ui
{
    public partial class LoginForm : Form
    {
        private class SMeta
        {
            public SMeta(ServerType tp, string desc) { _stype = tp; _desc = desc; }
            private ServerType _stype;
            public ServerType Stype { get { return _stype; } set { _stype = value; } }
            private string _desc;
            public string Desc { get { return _desc; } set { _desc = value; } }
        }
        private MainForm _form;
        private List<SMeta> _serverMetas;
        private Dictionary<ServerType, List<AccountData>> _users;
        private AccountData _acc_to_login;
        private LoginResult _login_result;
        public LoginForm(MainForm form)
        {
            _form = form;
            InitializeComponent();
            _users = new Dictionary<ServerType, List<AccountData>>();
            _serverMetas = new List<SMeta>();
            foreach (ServerType tp in Enum.GetValues(typeof(ServerType)))
            {
                _serverMetas.Add(new SMeta(tp, EnumString.getString(tp)));
            }
            comboServerList.DataSource = _serverMetas;
            comboServerList.DisplayMember = "Desc";
            loadUsers();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            _acc_to_login = collectUserInfo();
            if (_acc_to_login == null) return;
            if (_acc_to_login.Server_type == ServerType.Custom)
            {
                _form.initGame(_acc_to_login, null);
                this.Close();
                return;
            }
            login_worker.CancelAsync();
            btn_refresh_verify_code.Enabled = false;
            txt_verify_code.Enabled = false;
            btn_login.Enabled = false;
            login_worker.RunWorkerAsync();
        }
        private void loadUsers()
        {
            GlobalConfig.getInstance().loadSettings();
            _users = GlobalConfig.getInstance().getAllAccountByType();
            AccountData lastlogin = GlobalConfig.getInstance().getLastLoginAccount();

            int index_lastlogin = -1;
            if (_users.Count > 0) index_lastlogin = 0;
            if (lastlogin != null)
            {
                for (int i = 0; i < _serverMetas.Count; i++)
                {
                    if (_serverMetas[i].Stype == lastlogin.Server_type)
                    {
                        index_lastlogin = i;
                        break;
                    }
                }
            }

            comboServerList.SelectedIndex = index_lastlogin;
            getServerUsers();
        }
        private void getServerUsers()
        {
            SMeta meta = comboServerList.SelectedItem as SMeta;
            if (meta == null) return;
            if (!_users.ContainsKey(meta.Stype)) return;
            List<AccountData> ulst = _users[meta.Stype];
            if (meta.Stype == ServerType.Custom)
            {
                txt_customLoginUrl.Enabled = true;
                txt_customGameUrl.Enabled = true;
                combo_username.Enabled = false;
                txt_serverId.Enabled = false;
                txt_password.Enabled = false;
                txt_roleName.Enabled = true;
                combo_username.Text = "";
                txt_serverId.Value = 0;
                txt_password.Text = "";
                if (ulst.Count == 0) return;
                AccountData acc_custom = ulst[0];
                txt_roleName.Text = acc_custom.RoleName;
                txt_customLoginUrl.Text = acc_custom.CustomLoginUrl;
                txt_customGameUrl.Text = acc_custom.CustomGameUrl;
            }
            else
            {
                txt_customLoginUrl.Enabled = false;
                txt_customGameUrl.Enabled = false;
                combo_username.Enabled = true;
                txt_serverId.Enabled = true;
                txt_password.Enabled = true;
                txt_roleName.Enabled = true;
                txt_roleName.Text = "";
                txt_customLoginUrl.Text = "";
                txt_customGameUrl.Text = "";

                combo_username.DataSource = ulst;
            }
            AccountData lastlogin = GlobalConfig.getInstance().getLastLoginAccount();

            if (ulst.Count > 0)
            {
                int index_lastlogin = 0;
                if (lastlogin != null)
                {
                    for (int i = 0; i < ulst.Count; i++)
                    {
                        if (ulst[i].UserName == lastlogin.UserName && ulst[i].RoleName == lastlogin.RoleName)
                        {
                            index_lastlogin = i;
                            break;
                        }
                    }
                }
                if (meta.Stype != ServerType.Custom) combo_username.SelectedIndex = index_lastlogin;
            }
            else
            {
                combo_username.Text = "";
                txt_serverId.Value = 0;
                txt_password.Text = "";
                txt_roleName.Text = "";
            }
        }
        private void getUserInfo()
        {
            AccountData dt = combo_username.SelectedItem as AccountData;
            if (dt == null)
            {
                txt_serverId.Value = 0;
                txt_password.Text = "";
                txt_roleName.Text = "";
                return;
            }
            txt_serverId.Value = dt.ServerId;
            txt_password.Text = dt.Password;
            txt_roleName.Text = dt.RoleName;
        }
        private void comboServerList_SelectedIndexChanged(object sender, EventArgs e)
        {
            getServerUsers();
        }

        private void combo_username_SelectedIndexChanged(object sender, EventArgs e)
        {
            getUserInfo();
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {

        }

        private AccountData collectUserInfo()
        {
            if (comboServerList.SelectedIndex < 0)
            {
                UiUtils.getInstance().info("大虾，表糊弄我了，表还没填完呢，想进去免谈！！");
                return null;
            }
            SMeta stype_meta = comboServerList.SelectedItem as SMeta;
            if (stype_meta.Stype == ServerType.Custom)
            {
                if (txt_customLoginUrl.Text == "" || txt_customGameUrl.Text == "")
                {
                    UiUtils.getInstance().info("大虾，表糊弄我了，表还没填完呢，想进去免谈！！");
                    return null;
                }
            }
            else
            {
                if (txt_serverId.Value <= 0 || combo_username.Text == "" || txt_password.Text == "")
                {
                    UiUtils.getInstance().info("大虾，表糊弄我了，表还没填完呢，想进去免谈！！");
                    return null;
                }
            }

            int serverId = (int)(txt_serverId.Value);
            string roleName = txt_roleName.Text;
            string username = combo_username.Text;
            string password = txt_password.Text;
            string customLoginUrl = txt_customLoginUrl.Text;
            if (customLoginUrl.IndexOf("http://") < 0 && customLoginUrl.IndexOf("https://") < 0) customLoginUrl = "http://" + customLoginUrl;
            string customGameUrl = txt_customGameUrl.Text;
            if (customGameUrl.IndexOf("http://") < 0 && customGameUrl.IndexOf("https://") < 0) customGameUrl = "http://" + customGameUrl;
            bool found = false;
            AccountData login_acc = null;
            if (combo_username.DataSource != null)
            {
                List<AccountData> ulst = combo_username.DataSource as List<AccountData>;
                foreach (AccountData acc in ulst)
                {
                    if (acc.UserName.Equals(username) && acc.RoleName == roleName)
                    {
                        found = true;
                        login_acc = acc;
                        break;
                    }
                }
            }

            if (!found)
            {
                AccountData dt = new AccountData();
                dt.Server_type = stype_meta.Stype;
                dt.ServerId = serverId;
                dt.UserName = username;
                dt.Password = password;
                dt.RoleName = roleName;
                dt.CustomLoginUrl = customLoginUrl;
                dt.CustomGameUrl = customGameUrl;
                dt.IsLastLogin = true;
                GlobalConfig.getInstance().addAccount(dt);
                login_acc = dt;
            }
            else
            {
                login_acc.Server_type = stype_meta.Stype;
                login_acc.ServerId = serverId;
                login_acc.UserName = username;
                login_acc.Password = password;
                login_acc.RoleName = roleName;
                login_acc.CustomLoginUrl = customLoginUrl;
                login_acc.CustomGameUrl = customGameUrl;
                login_acc.IsLastLogin = true;
                GlobalConfig.getInstance().setLastLoginAccount(login_acc);
            }
            return login_acc;
        }
        private void login_worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string verify_code = txt_verify_code.Text;
            CommonReceiver recv = new CommonReceiver(_acc_to_login, login_worker);
            if (_login_result != null && _login_result.StatusCode == LoginStatusCode.NeedVerifyCode)
            {
                List<Cookie> web_cookies = _login_result.WebCookies;
                _login_result = LoginMgr.getInstance().doLogin(recv, ref web_cookies, verify_code, _login_result.CaptchaExtra);
            }
            else
            {
                List<Cookie> web_cookies = new List<Cookie>();
                _login_result = LoginMgr.getInstance().doLogin(recv, ref web_cookies);
            }
            e.Result = _login_result;
        }
        private void login_worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            string state = e.UserState as string;
            if (state == null) return;
            lbl_login_status.Text = state;
        }
        private void login_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btn_login.Enabled = true;
            LoginResult state = e.Result as LoginResult;
            if (state == null)
            {
                lbl_login_status.Text = "登录失败, 请重试下吧";
                return;
            }
            string result_tip = state.StatusDesc; 
            bool success = state.StatusCode == LoginStatusCode.Success;
            if (state.StatusCode == LoginStatusCode.NeedVerifyCode)
            {
                img_verify_code.Image = state.CaptchaImage;
                btn_refresh_verify_code.Enabled = true;
                txt_verify_code.Enabled = true;
            }
            if (!success)
            {
                lbl_login_status.Text = result_tip;
                return;
            }
            _form.initGame(_acc_to_login, state);
            this.Close();
        }
        private void btn_refresh_verify_code_Click(object sender, EventArgs e)
        {
            if (_login_result == null)
            {
                UiUtils.getInstance().error("程序出错了, 请关闭重新打开");
                return;
            }
            List<Cookie> web_cookies = _login_result.WebCookies;
            Image img = LoginMgr.getInstance().getCaptchaImage(_login_result.CaptchaUrl, ref web_cookies);
            img_verify_code.Image = img;
        }

        private void LoginForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (login_worker.CancellationPending) return;
            if (login_worker.IsBusy)
            {
                login_worker.CancelAsync();
            }
        }

        private void btn_delAccount_Click(object sender, EventArgs e)
        {
            if (comboServerList.SelectedIndex < 0) return;
            AccountData acc = new AccountData();
            SMeta stype_meta = comboServerList.SelectedItem as SMeta;
            int serverId = (int)(txt_serverId.Value);
            string roleName = txt_roleName.Text;
            string username = combo_username.Text;
            string password = txt_password.Text;
            acc.Server_type = stype_meta.Stype;
            acc.ServerId = serverId;
            acc.UserName = username;
            acc.Password = password;
            acc.RoleName = roleName;
            if (acc.UserName == "" || acc.ServerId == 0) return;

            GlobalConfig.getInstance().delAccount(acc);
            loadUsers();
        }
    }
}
